import { Login } from "@/api/interface";

import { User } from "@/api/interface/index";
import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";
import type { ElForm, MessageHandler } from "element-plus";
import { useRouter } from "vue-router";
import DialogBox from "../../../components/DialogBox";
import { getHome } from "../../../utils/routerUtil";
import Register from "./register";
import ResetPassword from "./resetPassword";
import { PublicStore } from "@/stores/modules/public";
import { ComponentInternalInstance, getCurrentInstance } from "vue";

const LoginPassword = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		type FormInstance = InstanceType<typeof ElForm>;
		const loginFormRef = ref<FormInstance>();
		const globalStore = GlobalStore();
		const publicStore = PublicStore();
		const authStore = AuthStore();
		const router = useRouter();
		const loading = ref(false);
		const loginRules = reactive({
			username: [{ required: true, message: proxy?.$t("login.rules.username"), trigger: "change" }],
			password: [{ required: true, message: proxy?.$t("login.rules.password"), trigger: "change" }]
		});
		const loginForm = reactive<Login.ReqLoginForm>({
			username: "",
			password: "",
			rememberUser: globalStore.setting.rememberUser ?? false
		});
		const rememberUserChange = (val: any) => {
			globalStore.rememberUser(val);
		};
		onMounted(() => {
			authStore.logout();
			if (import.meta.env.DEV) {
				loginForm.username = "admin";
				loginForm.password = "123456";
			}
			if (globalStore.setting.rememberUser) {
				loginForm.username = globalStore.setting.username ?? "";
			}
		});
		const login = (formEl: FormInstance) => {
			formEl.validate(async (valid: boolean) => {
				if (!valid) return;
				loading.value = true;
				const err: MessageHandler | string | undefined = await authStore.login(loginForm);
				if (err != null) {
					loading.value = false;
					return;
				}
				// 4.跳转到首页
				// 默认主页无法访问时导致系统无法使用，暂不启用
				if (publicStore.userInfo.id != "1" && globalStore.setting.home) {
					let token = "";
					if (RegExp(/\?.+=.*/).test(globalStore.setting.home)) {
						token = `&token=${publicStore.token}`;
					} else {
						token = `?token=${publicStore.token}`;
					}
					let server = globalStore.setting.home + token;
					window.location.href = server;
				} else {
					router.push(getHome());
				}
				// loading.value = false;
			});
		};

		const registerDialog = reactive({
			visible: false,
			detail: { username: "", password: "" }
		});
		const submitRegister = () => {
			loginForm.username = registerDialog.detail.username;
			loginForm.password = registerDialog.detail.password;
			registerDialog.detail.username = "";
			registerDialog.detail.password = "";
			registerDialog.visible = false;
		};

		const resetPwdDialog = reactive({
			visible: false,
			detail: { username: "", password: "" }
		});
		return () => {
			return (
				<>
					<DialogBox
						class="register-dialog"
						hideFooter
						v-model:visible={registerDialog.visible}
						title={proxy?.$t("login.dialog_title.register")}
						width="1024px"
					>
						{registerDialog.visible ? (
							<Register
								detail={registerDialog.detail as User.ReqUserRegister}
								onBackLogin={() => (registerDialog.visible = false)}
								onSubmit={() => submitRegister()}
							/>
						) : null}
					</DialogBox>
					<DialogBox
						hideFooter
						v-model:visible={resetPwdDialog.visible}
						title={proxy?.$t("login.dialog_title.reset")}
						width="800px"
					>
						{resetPwdDialog.visible ? <ResetPassword onSubmit={() => (resetPwdDialog.visible = false)} /> : null}
					</DialogBox>
					<el-form
						model={loginForm}
						ref={loginFormRef}
						rules={loginRules}
						size="large"
						onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? login(loginFormRef.value as FormInstance) : null)}
					>
						<el-form-item prop="username" class="el-form-username">
							<el-input
								class="pb-2"
								v-model={loginForm.username}
								placeholder={proxy?.$t("login.input_placeholder.username")}
								v-slots={{
									prefix: () => {
										return <span class="iconfont iconuser"></span>;
									}
								}}
							></el-input>
						</el-form-item>
						<el-form-item prop="password" class="el-form-password">
							<el-input
								type="password"
								v-model={loginForm.password}
								placeholder={proxy?.$t("login.input_placeholder.password")}
								show-password
								v-slots={{
									prefix: () => {
										return <span class="iconfont iconbx-lock"></span>;
									}
								}}
							></el-input>
						</el-form-item>
						<el-form-item>
							<div class="w-full h-6 flex justify-between">
								<el-checkbox
									v-model={loginForm.rememberUser}
									onChange={rememberUserChange}
									label={proxy?.$t("login.checkbox.remember")}
									style="margin-top:-8px;"
								/>
								<el-link type="primary" onClick={() => (resetPwdDialog.visible = true)}>
									{proxy?.$t("login.link.forgotpwd")}
								</el-link>
							</div>
						</el-form-item>
					</el-form>
					<div class="login-btn flex">
						<el-button
							class="flex-1"
							onClick={() => login(loginFormRef.value as FormInstance)}
							size="large"
							type="primary"
							loading={loading.value}
						>
							{proxy?.$t("login.btn.login")}
						</el-button>
					</div>
					<div class="flex justify-center login-panel-register">
						<span>{proxy?.$t("login.text.no_account")} </span>
						<el-link type="primary" onClick={() => (registerDialog.visible = true)}>
							{proxy?.$t("login.link.register")}
						</el-link>
					</div>
					<div class="ext-tips">{proxy?.$t("login.tips.use_chrome")}</div>
				</>
			);
		};
	}
});
export default LoginPassword;
